import 'dart:math';

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DBHelper {
  final _dbName = "customDir/" + "${Random().nextInt(36000)}.db";
  final SQL_CREATE_TABLE = "CREATE VIRTUAL TABLE example USING fts4(name, content, tokenize=icu zh_CN)";
  Future<List<Map<String, Object?>>> setupDatabase() async {
    final databasePath = await getDatabasesPath();
    final path = join(databasePath, _dbName);

    final database = await openDatabase(
      path,
      version: 1,
      onCreate: (Database db, int version) async {
        // 创建FTS虚拟表
        await db.execute(SQL_CREATE_TABLE);
      },
    );

    // 插入数据
    await database.insert('example', {
      'name': 'jack',
      'content': 'This is a sample text for full-text search in Flutter 中国'
    });

    // 搜索
    final results = await database.query(
        'example',
        where: 'content MATCH ?',
        whereArgs: ['sample text']
    );
    print(results);
    return results;
  }
}